package operation_system.producer_consumer;

import java.util.LinkedList;
import java.util.concurrent.Semaphore;

//通过信号量实现
public class CMethod {
    private LinkedList<Object> list = new LinkedList<Object>();
    // 仓库的最大容量
    final Semaphore full = new Semaphore(10);
    // 将线程挂起，等待其他来触发
    final Semaphore empty = new Semaphore(0);
    // 互斥锁
    final Semaphore mutex = new Semaphore(1);

    public void produce(){
        try{
            //不能先申请mutex；如果先申请mutex，full阻塞则会导致，其他线程进入不了mutex临界区，从而导致活锁
            full.acquire();
            mutex.acquire();
            list.add(new Object());
            System.out.println("【生产者" + Thread.currentThread().getName()
                    + "】生产一个产品，现库存" + list.size());
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            mutex.release();
            empty.release();
        }
    }
    public void consume(){
        try{
            empty.acquire();
            mutex.acquire();
            list.remove();
            System.out.println("【消费者" + Thread.currentThread().getName()
                    + "】消费一个产品，现库存" + list.size());
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            mutex.release();
            full.release();
        }
    }
}
